﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Reflection;

namespace GrainManage.Data.Pattern
{
    public class LikePattern : IPattern
    {
        public string ContainModel(string parameter)
        {
            return string.IsNullOrEmpty(parameter) ? "%" : string.Format("%{0}%", parameter);
        }

        public string StartModel(string parameter)
        {
            return string.IsNullOrEmpty(parameter) ? "%" : string.Format("{0}%", parameter);
        }

        public string EndModel(string parameter)
        {
            return string.IsNullOrEmpty(parameter) ? "%" : string.Format("%{0}", parameter);
        }

        public string OriginalModel(string parameter)
        {
            return string.IsNullOrEmpty(parameter) ? "%" : parameter;
        }

        public string SplitModel(string parameter)
        {
            return string.IsNullOrEmpty(parameter) ? "%" : Regex.Replace(parameter, @"[\s]+", "%");
        }

        public string GetPatternModel(string parameter, PatternMode mode)
        {
            switch (mode)
            {
                case PatternMode.Contain:
                    return ContainModel(parameter);
                case PatternMode.Start:
                    return StartModel(parameter);
                case PatternMode.End:
                    return EndModel(parameter);
                case PatternMode.Split:
                    return SplitModel(parameter);
                default:
                    return OriginalModel(parameter);
            }
        }

        public void SetModel<TEntity>(TEntity entityFilter, PatternMode mode) where TEntity : class
        {
            foreach (var item in typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            {
                if (item.PropertyType == typeof(string))
                {
                    item.SetValue(entityFilter, GetPatternModel(item.GetValue(entityFilter, null) as string, PatternMode.Contain), null);
                }
            }
        }


        public DateTime? GetDateTime(string time)
        {
            DateTime dt;
            if (DateTime.TryParse(time, out dt))
            {
                return dt;
            }
            else
            {
                return null;
            }
        }
    }
}
